<template>
  <!-- 服务设置 -->
  <div class="tablePageWarp">
    <div class="commonSelectWidth table-page-search-wrapper">
      <a-row :gutter="16">
        <a-col :md="3" :sm="24">
          <service-belong-select
            :default-value="queryParam.serviceBelong"
            mode="multiple"
            :maxTagCount="1"
            @changeoption="changeoption($event, 'serviceBelong')"
          >
          </service-belong-select>
        </a-col>
        <a-col :md="3" :sm="24">
          <service-sale-cate-select
            :default-value="queryParam.serviceCategory"
            mode="multiple"
            :maxTagCount="1"
            @changeoption="changeoption($event, 'serviceCategory')"
          >
          </service-sale-cate-select>
        </a-col>
        <a-col :md="3" :sm="24">
          <need-to-learn-select
            :default-value="queryParam.needStudy"
            placeholderText="qxzsfxx"
            @changeoption="changeoption($event, 'needStudy')"
            style="width: 100%"
          >
          </need-to-learn-select>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-input
            v-model.trim="queryParam.serviceCode"
            :placeholder="$t('serviceCode')"
            @keyup.enter="refreshData"
            allowClear
          />
        </a-col>
        <a-col :md="3" :sm="24">
          <a-input
            v-model.trim="queryParam.serviceName"
            :placeholder="$t('serviceName')"
            @keyup.enter="refreshData"
            allowClear
          />
        </a-col>
        <a-col :md="7" :sm="24">
          <div class="searchBtns" style="display: flex">
            <a-button-group>
              <auth-button :auth="softwarePerms.serviceConfig.view" @click="refreshData" type="primary">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="initiSelectValue">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <auth-button :auth="softwarePerms.serviceConfig.add" @click="handleEdit()">
              <i class="iconfont icon-xinjian"></i>
              {{ $t('service') }}
            </auth-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <s-table
      ref="table"
      class="h100 withMinHeightTbodyBox"
      :rowKey="(record, index) => record.id"
      :columns="serviceColumns"
      :data="loadData"
      :scrollX="1400"
    >
      <template
        slot-scope="text"
        v-for="column in serviceColumns.filter((item) => !item.special)"
        :slot="column.scopedSlots.customRender"
      >
        <table-ellipsis :text="text || '_'" :key="column.dataIndex"> </table-ellipsis>
      </template>
      <template #serviceDetail="text, record">
        <a @click="handleDetail(record)">
          <table-ellipsis :text="text"> </table-ellipsis>
        </a>
      </template>
      <template #fwgsy="text">
        <table-ellipsis :text="serviceSaleBelongFlagDictCodeObj[text]"></table-ellipsis>
      </template>
      <template #fwfl="text">
        <table-ellipsis :text="serviceSaleCateFlagDictCodeObj[text]"></table-ellipsis>
      </template>
      <template #needToLearn="text">
        <table-ellipsis :text="chooseYesNoTypeObj[text]"></table-ellipsis>
      </template>
      <template slot="connectedModelsTile">
        <span>{{ $t('connectedModel') }}</span>
        <question-mark-tip
          :tip-title="$t('serviceRelativeModelTip')"
          :popupContainer="$commonFun.getPopupContainer"
        ></question-mark-tip>
      </template>
      <template slot="yglcxTile">
        <span>{{ $t('managedModel') }}</span>
        <question-mark-tip
          :tip-title="$t('serviceManageTip')"
          :popupContainer="$commonFun.getPopupContainer"
        ></question-mark-tip>
      </template>
      <template slot="yglcx" slot-scope="text">
        <i class="iconfont icon-chexing"></i>
        <span style="font-weight: bolder"> {{ text }}</span>
      </template>

      <template slot="createTime" slot-scope="text">
        <table-ellipsis v-if="text" :text="$options.filters.moment(text)"></table-ellipsis>
        <span v-else>_</span>
      </template>
      <span slot="action" slot-scope="text, record" class="tableOperateSty">
        <auth-button
          type="primary"
          :ghost="true"
          size="small"
          :auth="softwarePerms.serviceConfig.edit"
          @click="handleEdit(record)"
          :disabled="!record.allowEdit"
        ><i class="iconfont icon-xiugai"/>{{
          $t('edit')
        }}</auth-button>
        <auth-button
          type="danger"
          :ghost="true"
          size="small"
          :auth="softwarePerms.serviceConfig.delete"
          @click="deleteList(record)"
          :disabled="!record.allowDel"
        ><i class="iconfont icon-shanchu3 deleteUlr"/>{{
          $t('delete')
        }}</auth-button>
      </span>
    </s-table>
  </div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import ServiceDetail from '@/views/components/ServiceDetail.vue'
import needToLearnSelect from '@/views/components/needToLearnSelect'
import ServiceBelongSelect from '@/views/components/ServiceBelongSelect'
import ServiceSaleCateSelect from '@/views/components/ServiceSaleCateSelect'
import EditService from './components/EditService.vue'
import EditServiceBelong from './components/EditServiceBelong.vue'
import { STable } from '@/components'
import { minxinDrawerUse } from '@/utils/mixin'
import modelApi from '@/api/modules/system/modelMana'
import AuthButton from '@/components/AuthButton'
import { softwarePerms } from '@/config/permission/index'
import AuthText from '@/components/AuthText'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import { serviceColumns } from './configConst'
export default {
  name: 'ServiceConfigPage',
  mixins: [minxinDrawerUse],
  components: {
    TableEllipsis,
    HasNoPermissionTip,
    ServiceDetail,
    EditService,
    STable,
    AuthButton,
    needToLearnSelect,
    ServiceBelongSelect,
    ServiceSaleCateSelect,
    AuthText,
    QuestionMarkTip
  },
  data () {
    return {
      serviceColumns,
      softwarePerms,
      queryParam: {},
      editTypeTag: '',
      deleteId: '',
      modelOptionsArr: [],
    }
  },
  watch: {
    rightDrawerEvent (val) {
      const vm = this
      if (val) {
        vm.editTypeTag = val
        vm.handleEditSeviceBelongCate(val)
      }
    }
  },
  computed: {
    ...mapState({
      rightDrawerEvent: (state) => state.serviceConfig.rightDrawerEvent,
      newServiceData: (state) => state.serviceConfig.newServiceData,
      instantUpdateTime: (state) => state.app.instantUpdateTime,
    }),
    serviceSaleBelongFlagDictCodeObj () {
      return this.$store.getters.getDictCodeObj('serviceSaleBelongFlagDictCode')
    },
    serviceSaleCateFlagDictCodeObj () {
      return this.$store.getters.getDictCodeObj('serviceSaleCateFlagDictCode')
    },
    chooseYesNoTypeObj () {
      return this.$store.getters.chooseYesNoTypeObj()
    }
  },
  mounted () {
    this.initiSelectValue()
    this.$store.dispatch('getServiceSaleCateFlagDictCodeData')
    this.$store.dispatch('getServiceSaleBelongFlagDictCodeData')
  },
  methods: {
    ...mapMutations([ 'SET_ServieceRightDrawerEvent']),
    changeoption (event, key) {
      const vm = this
      vm.$set(vm.queryParam, key, event)
      this.refreshData();
    },
    // 下拉框 重置和初始化
    initiSelectValue () {
      this.queryParam = {}
      this.refreshData()
    },
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      return vm.$api.getServiceConfigList({ ...parameter, ...JnqueryParam })
    },
    // 服务详情
    handleDetail (recordData) {
      const vm = this
      const vars = { serviceId: recordData.id }
      vm.showRightDrawer(ServiceDetail, vm.$t('serviceDetail'), [], 'large', vars)
    },
    // 新建编辑服务
    async handleEdit (recordData = {}, isBack = false) {
      this.modelOptionsArr = await this.getModelCode()
      const vm = this
      const buttons = this.getRightDrawerFooterButtons()
      const vars = { recordData, isBack}
      vm.showRightDrawer(
        EditService,
        recordData.id ? vm.$t('editService') : vm.$t('newService'),
        buttons,
        'large',
        vars
      )
      this.SET_ServieceRightDrawerEvent('')
    },
    // 新增编辑服务归属域，服务分类弹框
    handleEditSeviceBelongCate (tag) {
      const vm = this
      const buttons = [
        {
          key: '',
          title: 'back',
          type: 'primary',
          name: 'backBtn',
          method: vm.backToServiceEdit,
          callback: null,
          loading: false,
          disabled: false
        }
      ]
      const headerButtons = [
        {
          type: '',
          method: vm.addSeviceBelongCate,
          iconCls: 'icon-xinjian',
          class: 'headerBtnClas'
        }
      ]
      vm.setDrawerConfig({
        compName: EditServiceBelong,
        title: vm.$t('edit') + vm.$t(tag),
        footerButtons: buttons,
        headerButtons,
        vars: { editWhich: tag },
        width: 'large'
      })
    },
    // 新增服务归属域和分类
    addSeviceBelongCate (comp) {
      comp.addList()
    },
    // 返回编辑或新增车型页面
    backToServiceEdit () {
      const vm = this
      vm.handleEdit(vm.newServiceData, true)
    },
    // 编辑提交
    saveData (values) {
      const vm = this
      const params = vm.$commonFun.deepCopy(values)
      params.apiStr = undefined
      let tempArr = []
      this.modelOptionsArr.forEach(e => {
        if (params.modelDtoList.includes(e.id)) {
          tempArr.push({ code: e.code, id: e.id, trimLevel: e.trimLevel })
        }
      })
      params.modelDtoList = tempArr
      return new Promise((resolve, reject) => {
        vm.$api[values.apiStr](params)
          .then((res) => {
            vm.refreshData(!values.id)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    refreshData (isToFirstPage = true) {
      const vm = this
      vm.$nextTick(() => {
        vm.$refs.table && vm.$refs.table.refresh(isToFirstPage)
      })
    },
    deleteList (record) {
      const vm = this
      vm.deleteId = record.id
      this.$confirm({
        title: vm.$t('delete') + vm.$t('serviceConfig'),
        content: this.$t('deleteConfirmNotice').replace('__CONTENT__', this.$t('serviceConfig')),
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk: this.deleteOk,
        onCancel () {}
      })
    },
    getModelCode () {
      return new Promise(((resolve) => {
        modelApi.getMyAllModelCode({ time: this.instantUpdateTime, selectAll: false,pageSize:100000 }).then((res) => {
          let data = res.data
          if (!data) {
            return
          }
          data = data.map(item => {
            let showName = item.code
            showName += (item.name ? '[' + item.name + ']' : '')
            return {
              id: item.code,
              ...item,
              showName,
              code: item.code,
              title: item.name
            }
          })
          resolve(data)
      })
      }))
    },
    deleteOk () {
      const vm = this
      vm.$api.deleteServiceConfig({ id: vm.deleteId }).then(() => {
        vm.$message.success(vm.$t('successfullyDelete'))
        vm.refreshData(false) // 刷新页面
      })
    }
  }
}
</script>
